import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
import HomeView from "../views/HomeView.vue";
import NProgress from "@/config/nprogress";

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: HomeView,
      redirect: "/home",
      children: [
        {
          path: "/test",
          name: "test",
          component: () => import("@/views/test/Test.vue"),
        },
        {
          path: "/home",
          name: "homeIndex",
          component: () => import("@/views/home/Home.vue"),
        },
        {
          // 菜单管理
          path: "/menuManage",
          name: "menuManage",
          component: () => import("@/views/menuManage/MenuManage.vue"),
        },
        {
          // 用户管理
          path: "/userManage",
          name: "userManage",
          component: () => import("@/views/userManage/UserManage.vue"),
        },
        {
          // 角色管理
          path: "/roleManage",
          name: "roleManage",
          component: () => import("@/views/roleManage/roleManage.vue"),
        },
        {
          // 图片管理
          path: "/imageManage",
          name: "imageManage",
          // redirect: "/imageManage/category",
          component: () => import("@/views/imageManage/imageManage.vue"),
          children: [
            {
              // 图片分类
              path: "category",
              name: "category",
              component: () => import("@/views/imageManage/Category.vue"),
            },
            {
              // 图片列表
              path: "imageList",
              name: "imageList",
              component: () => import("@/views/imageManage/imageList.vue"),
            },
          ],
        },

        {
          // 资讯管理
          path: "/msgManage",
          name: "msgManage",
          redirect: "/msgManage/list",
          component: () => import("@/views/msgManage/Index.vue"),
          children: [
            {
              // 资讯列表
              path: "list",
              name: "list",
              component: () => import("@/views/msgManage/List.vue"),
            },
          ],
        },
      ],
    },
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/Login.vue"),
    },
  ],
});

router.beforeEach((to, form, next) => {
  NProgress.start();
  const token = localStorage.getItem("token");

  if (!token && to.name != "login") {
    next("/login");
  } else {
    next();
  }
});

/**
 * @description 路由跳转错误
 * */
router.onError((error) => {
  NProgress.done();
  console.warn("路由错误", error.message);
});

/**
 * @description 路由跳转结束
 * */
router.afterEach(() => {
  NProgress.done();
});

export default router;
